//
//  TCLoginModel.m
//  TCLVBIMDemo
//
//  Created by dackli on 16/8/3.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "TCLoginModel.h"
//#import "TCUserInfoModel.h"
//#import "TCLiveListModel.h"
//#import "TCConstants.h"
#import "TCUtil.h"
#ifndef APP_EXT
//#import "AppDelegate.h"
#endif
#import "AFNetworking.h"
#import "NSString+Common.h"
//#import "TCLiveListModel.h"

#define kAutoLoginKey         @"kAutoLoginKey"
#define kEachKickErrorCode    6208   //互踢下线错误码


@interface TCLoginModel()
{
    TCLoginParam *_loginParam;

}
@property (nonatomic, copy) NSString* refreshToken;
@property (nonatomic, assign) int64_t expires;
@property (nonatomic, copy) NSString* sign;
@property (nonatomic, copy) NSString* txTime;
@property (nonatomic, copy) NSString* accountType;
@property (nonatomic, assign) int sdkAppID;
@end

@implementation TCLoginModel

static TCLoginModel *_sharedInstance = nil;

+ (instancetype)sharedInstance {
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        _sharedInstance = [[TCLoginModel alloc] init];
    });
    return _sharedInstance;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        _loginParam = [TCLoginParam loadFromLocal];
    }
    return self;
}

+ (BOOL)isAutoLogin {
    NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:APP_GROUP];
    if (defaults == nil) {
        defaults = [NSUserDefaults standardUserDefaults];
    }
    NSNumber *num = [defaults objectForKey:kAutoLoginKey];
    return [num boolValue];
}

+ (void)setAutoLogin:(BOOL)autoLogin {
    NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:APP_GROUP];
    if (defaults == nil) {
        defaults = [NSUserDefaults standardUserDefaults];
    }
    [defaults setObject:@(autoLogin) forKey:kAutoLoginKey];
}

- (void)registerWithUsername:(NSString *)username password:(NSString *)password succ:(TCRegistSuccess)succ fail:(TCRegistFail)fail
{
    NSString* pwdMD5 = [password md5];
    NSString* hashPwd = [[pwdMD5 stringByAppendingString:username] md5];
    
    NSDictionary* params = @{@"userid": username, @"password": hashPwd};
    
    [TCUtil asyncSendHttpRequest:@"register" params:params handler:^(int resultCode, NSString *message, NSDictionary *resultDict) {
        NSLog(@"%d, %@, %@", resultCode, message, resultDict.description);
        if (resultCode == 200) {
            succ(username, hashPwd);
        }
        else {
            fail(resultCode, message);
        }
    }];
}

- (void)loginWithUsername:(NSString *)username password:(NSString *)password succ:(TCLoginSuccess)succ fail:(TCLoginFail)fail
{
    NSString* pwdMD5 = [password md5];
    NSString* hashPwd = [[pwdMD5 stringByAppendingString:username] md5];
    
    [self loginByToken:username hashPwd:hashPwd succ:succ fail:fail];
}

- (void)loginByToken:(NSString*)username hashPwd:(NSString*)hashPwd succ:(TCLoginSuccess)succ fail:(TCLoginFail)fail
{
    NSDictionary* params = @{@"userid": username, @"password": hashPwd};
    __weak typeof(self) weakSelf = self;

    [TCUtil asyncSendHttpRequest:@"login" params:params handler:^(int resultCode, NSString *message, NSDictionary *resultDict) {
        if (resultCode == 200) {
            weakSelf.token = resultDict[@"token"];
            weakSelf.expires = ((NSNumber*)resultDict[@"expires"]).unsignedLongLongValue;
            weakSelf.refreshToken = resultDict[@"refresh_token"];
            if (resultDict[@"roomservice_sign"]) {
                weakSelf.sign = resultDict[@"roomservice_sign"][@"userSig"];
                weakSelf.accountType = resultDict[@"roomservice_sign"][@"accountType"];
                weakSelf.sdkAppID = ((NSNumber*)resultDict[@"roomservice_sign"][@"sdkAppID"]).intValue;
            }
            
//            if (resultDict[@"cos_info"]) {
//                [[TCUserInfoModel sharedInstance] setBucket:resultDict[@"cos_info"][@"Bucket"] secretId:resultDict[@"cos_info"][@"SecretId"]
//                                        appid:[resultDict[@"cos_info"][@"Appid"] longLongValue] region:resultDict[@"cos_info"][@"Region"] accountType:weakSelf.accountType];
//            }
//            
//            [[TCUserInfoModel sharedInstance] setIdentifier:username expires:@(weakSelf.expires) token:weakSelf.token];
//            [[TCLiveListMgr sharedMgr] setUserId:username expires:@(weakSelf.expires) token:weakSelf.token];
            
            _loginParam.identifier = username;
            _loginParam.hashedPwd = hashPwd;
            _loginParam.token = weakSelf.token;
            [TCLoginModel setAutoLogin:YES];
            
            succ(username, hashPwd ,weakSelf.token);
        }
        else {
            fail(resultCode, message);
        }
    }];
}

- (void)logout:(TCLogoutComplete)completion {
    [TCLoginModel setAutoLogin:NO];
    [[NSNotificationCenter defaultCenter] postNotificationName:logoutNotification object:nil];
    if (completion) {
        completion();
    }
    self.token = nil;
    self.refreshToken = nil;
    self.sign = nil;
    self.expires = 0;
    self.txTime = nil;
}

- (TCLoginParam *)getLoginParam {
    if (_loginParam) {
        return _loginParam;
    }
    return [[TCLoginParam alloc] init];
}

- (void)getCosSign:(void (^)(int, NSString *, NSDictionary *))completion
{
    NSDictionary* params = @{@"userid": _loginParam.identifier, @"timestamp":@([[NSDate date] timeIntervalSince1970] * 1000), @"expires":@(self.expires)};
    
    [TCUtil asyncSendHttpRequest:@"get_cos_sign" token:_loginParam.token params:params handler:^(int resultCode, NSString *message, NSDictionary *resultDict) {
        completion(resultCode, message, resultDict);
    }];
}

- (void)getVodSign:(void (^)(int, NSString *, NSDictionary *))completion
{
    NSDictionary* params = @{@"userid": _loginParam.identifier, @"timestamp":@([[NSDate date] timeIntervalSince1970] * 1000), @"expires":@(self.expires)};
    [TCUtil asyncSendHttpRequest:@"get_vod_sign" token:_loginParam.token params:params handler:^(int resultCode, NSString *message, NSDictionary *resultDict) {
        completion(resultCode, message, resultDict);
    }];
}

- (void)uploadUGC:(NSDictionary *)params completion:(void (^)(int, NSString *, NSDictionary *))completion
{
    NSDictionary* hparams = @{@"userid": _loginParam.identifier, @"timestamp":@([[NSDate date] timeIntervalSince1970] * 1000), @"expires":@(self.expires)};

    NSMutableDictionary* mparams = [NSMutableDictionary dictionaryWithDictionary:hparams];
    [mparams addEntriesFromDictionary:params];
    
    [TCUtil asyncSendHttpRequest:@"upload_ugc" token:_loginParam.token params:mparams handler:^(int resultCode, NSString *message, NSDictionary *resultDict) {
        completion(resultCode, message, resultDict);
    }];
}

@end
